import React, { ReactElement, InputHTMLAttributes, ChangeEvent, forwardRef } from "react";
import classNames from "classnames";
import { IconProp } from "@fortawesome/fontawesome-svg-core";
import Icon from "../Icon/icon";

type InputSize = "lg" | "ml" | "sm";
export interface InputProps extends Omit<InputHTMLAttributes<HTMLElement>, "size"> {
  className?: string;
  disabled?: boolean;
  style?: React.CSSProperties;
  size?: InputSize;
  icon?: IconProp;
  prepend?: string | ReactElement;
  append?: string | ReactElement;
  onChange?: (e: ChangeEvent<HTMLInputElement>) => void;
}

export const Input = forwardRef<HTMLInputElement, InputProps>((props, ref) => {
  const { className, disabled, style, size, icon, prepend, append, children, ...restProps } = props;
  const classes = classNames("lister-input-wrapper", {
    [`input-size-${size}`]: size,
    [`input-${icon}`]: icon,
    "is-disabled": disabled,
    "input-group": prepend || append,
    "input-group-append": !!append,
    "input-group-prepend": !!prepend,
  });
  const fixControlledValue = (value: any) => {
    if (value === undefined || value === null) {
      return "";
    }
    return value;
  };
  if ("value" in props) {
    delete restProps.defaultValue;
    restProps.value = fixControlledValue(props.value);
  }
  return (
    <div className={classes} style={style}>
      {prepend && <div className="lister-input-group-prepend">{prepend}</div>}
      {icon && (
        <div className="icon-wrapper">
          <Icon icon={icon} title={`title-${icon}`} />
        </div>
      )}
      <input ref={ref} className="lister-input-inner" disabled={disabled} {...restProps} />
      {append && <div className="lister-input-group-append">{append}</div>}
    </div>
  );
});

export default Input;

Input.defaultProps = {
  size: 'ml',
  disabled: false
}
